package com.foreknow.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Hashtable;

/**
 * java中的反射机制
 *
 */
public class ReflectionDemo {
    public void getNameTest(){
        String name = "tom123";
        Class clazz = name.getClass();
        System.out.println(clazz.getName());

    }
    public String testMethod(String str, Hashtable hashtable){
        String s = "这是我们要返回的方法";
        System.out.println(hashtable.get("name"));
        return s;
    }
    public void getMethodtest() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class cls = Class.forName("com.foreknow.reflection");
        //方法的参数列表
        Class[] classes = new Class[2];
        classes[0]=Class.forName("java.lang.String");
        classes[1]=Class.forName("java.util.Hashtable");
        Method method = cls.getMethod("testMethod", classes);
        Object[] objects = new Object[2];
        objects[0]="这是一个实参";
        Hashtable<String, Integer> hashtable = new Hashtable<>();
        hashtable.put("name",1);
        objects[1]=hashtable;
        method.invoke(new ReflectionDemo(), objects);
    }

    public static void main(String[] args) {
        ReflectionDemo demo = new ReflectionDemo();
        demo.getNameTest();
        Hashtable<String, Integer> hashtable = new Hashtable<>();
        hashtable.put("name",1);
        demo.testMethod("",hashtable);
    }
}
